package com.gtmc.gclub.chat.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gtmc.gclub.chat.dto.WxChatLogExportDto;
import com.gtmc.gclub.chat.vo.WxChatLogExportVo;

public class BeanMapUtil {

	public static void main(String[] args)throws Exception{
		WxChatLogExportDto test = new WxChatLogExportDto();
		System.out.println(convertBeanToMap(test));
	}
	
	public static Map<String,Object> convertBeanToMap(Object bean) throws IntrospectionException,IllegalAccessException, InvocationTargetException {
		Class type = bean.getClass();
		Map<String,Object> returnMap = new HashMap<String, Object>();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class")) {
				Method readMethod = descriptor.getReadMethod();
				Object result = readMethod.invoke(bean, new Object[0]);
				if (result != null) {
					returnMap.put(propertyName, result);
				} else {
					returnMap.put(propertyName, "");
				}
			}
		}
		return returnMap;
	}
	
//	public static List<Map<String,Object>> convertBeansToMap(List<Object> beans) throws IllegalAccessException, InvocationTargetException, IntrospectionException{
//		List<Map<String,Object>> res = new ArrayList<Map<String,Object>>();
//		for(Object obj:beans) {
//			Map<String,Object> entMap = new HashMap<String,Object>();
//			entMap = convertBeanToMap(obj);
//			res.add(entMap);
//		}
//		return res;
//	}

	public static List<Map<String, Object>> convertBeansToMap(List<WxChatLogExportVo> beans) throws IllegalAccessException, InvocationTargetException, IntrospectionException {
		List<Map<String,Object>> res = new ArrayList<Map<String,Object>>();
		for(WxChatLogExportVo obj:beans) {
			Map<String,Object> entMap = new HashMap<String,Object>();
			entMap = convertBeanToMap(obj);
			res.add(entMap);
		}
		return res;
	}

}
